/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved. distributed with this file and
 * available online at
 */
package com.lap.auth.application.region;

import java.util.List;
import org.springframework.stereotype.Service;
import com.lap.auth.application.region.assembler.RegionAssembler;
import com.lap.auth.application.region.command.CreateRegionCmd;
import com.lap.auth.application.region.command.UpdateRegionCmd;
import com.lap.auth.application.region.dto.RegionDto;
import com.lap.auth.application.region.dto.RegionViewDto;
import com.lap.auth.domain.region.Region;
import com.lap.auth.domain.region.repository.RegionRepository;
import com.lap.auth.domain.region.service.RegionValidator;
import lombok.RequiredArgsConstructor;

/**
 * 区域应用服务层
 *
 * <ol>
 * <li>不谈业务规则，只谈基础规则（加密/解密是技术实现，业务不关注）
 * <li>取数，赋值，对象转换到在这层执行
 * <li>命名有规范，动词+领域名字
 * <li>如查询比较多，建议分开领域QueryAppService,如:分页查询，分页查询返回关联字段
 * </ol>
 */
@RequiredArgsConstructor
@Service
public class RegionAppService {

  private final RegionAssembler regionAssembler;
  private final RegionValidator regionValidator;
  private final RegionRepository regionRepository;

  public RegionViewDto queryRegions(Integer pid) {
    RegionDto parent = regionRepository.findById(pid).map(regionAssembler::toDto).orElse(null);
    List<Region> list = regionRepository.findByPid(pid);
    return new RegionViewDto(parent, regionAssembler.toDtoList(list));
  }

  public Integer createRegion(CreateRegionCmd cmd) {
    Region region = regionAssembler.toDomain(cmd);
    region.initPidPath(() -> regionRepository.findById(region.getPid()));
    return regionRepository.save(region);
  }

  public int updateRegion(Integer id, UpdateRegionCmd cmd) {
    regionValidator.assertRegionExists(id);
    Region region = regionAssembler.toDomain(id, cmd);
    // TODO 修复数据使用
    if (region.getPid() != null) {
      region.initPidPath(() -> regionRepository.findById(region.getPid()));
    }
    return regionRepository.save(region);
  }

  public Integer deleteRegion(Integer id) {
    Region region = regionValidator.assertRegionExists(id);
    List<Region> children = regionRepository.findByPid(id);
    region.canDelete(children);
    return regionRepository.deleteById(id);
  }
}
